package world.snowcrystal.openapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import world.snowcrystal.commons.exception.BusinessException;
import world.snowcrystal.commons.model.entity.DailyInvokeLog;
import world.snowcrystal.commons.model.entity.InterfaceInvokeAnalysis;
import world.snowcrystal.commons.model.enums.ApplicationResponseStatusCode;
import world.snowcrystal.commons.service.AnalysisService;
import world.snowcrystal.openapi.mapper.DailyInvokeLogMapper;
import world.snowcrystal.openapi.mapper.UserInvokeLogMapper;

import java.util.Date;
import java.util.List;


@Service
public class AnalysisServiceImpl implements AnalysisService {


    @Resource
    private UserInvokeLogMapper userInvokeLogMapper;

    @Resource
    private DailyInvokeLogMapper dailyInvokeLogMapper;


    @Override
    public List<InterfaceInvokeAnalysis> retrieveTopNInvokedInterface(int limit) {
        if (limit < 0) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR, "limit must be greater than 0");
        }
        return userInvokeLogMapper.listTopNInvokeInterfaceCount(limit);
    }

    @Override
    public List<DailyInvokeLog> retrieveRecentInvokeLog(Date from, Date to) {
        if(from == null || to == null) {
            throw new BusinessException(ApplicationResponseStatusCode.PARAMS_ERROR, "from and to must not be null");
        }
        QueryWrapper<DailyInvokeLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.between("dateTime", from, to)
                .orderByAsc("dateTime");

        List<DailyInvokeLog> dailyInvokeLogs = dailyInvokeLogMapper.selectList(queryWrapper);
        if (dailyInvokeLogs == null) {
            throw new BusinessException(ApplicationResponseStatusCode.SYSTEM_ERROR, " fail to connect db ");
        }
        return dailyInvokeLogs;
    }
}
